const url = $request.url;
const method = $request.method;
const postMethod = "POST";
const notifyTitle = "贴吧json脚本错误";
console.log(`贴吧json-2024.10.20`);

let body;
try {
  body = JSON.parse($response.body);
} catch (e) {
  console.log(`JSON解析失败: ${e.message}`);
  $notification.post(notifyTitle, "JSON解析错误", e.message);
  $done({});
  return;
}

// 定义需要删除的关键词
const removeKeywords = ["直播", "高考"];

// 通用函数：移除标签
function removeTabKeywords(body) {
  let hasChanges = false;
  
  // 处理 index_tab_info 数组
  if (body.index_tab_info && Array.isArray(body.index_tab_info)) {
    const originalLength = body.index_tab_info.length;
    body.index_tab_info = body.index_tab_info.filter((item) => {
      if (item.tab_name) {
        return !removeKeywords.includes(item.tab_name);
      }
      return true;
    });
    if (body.index_tab_info.length < originalLength) {
      console.log(`移除了${originalLength - body.index_tab_info.length}个标签`);
      hasChanges = true;
    }
  }

  // 处理 top_level_navi 对象
  if (body.top_level_navi && typeof body.top_level_navi === "object") {
    removeKeywords.forEach((keyword) => {
      if (body.top_level_navi[keyword]) {
        delete body.top_level_navi[keyword];
        console.log(`移除top_level_navi中的${keyword}`);
        hasChanges = true;
      }
    });
  }
  
  return hasChanges;
}

// VIP伪装函数
function fakeVIPStatus(body) {
    console.log("开始伪装VIP状态");
    
    // 删除推荐的广告相关字段
    if (body.recom_naws_list) {
      delete body.recom_naws_list;
      console.log("删除recom_naws_list");
    }
    
    if (body.namoaixud_entry) {
      delete body.namoaixud_entry;
      console.log("删除namoaixud_entry");
    }
    
    if (body.custom_grid) {
      delete body.custom_grid;
      console.log("删除custom_grid");
    }
    
    if (body.duxiaoman_entry) {
      delete body.duxiaoman_entry;
      console.log("删除duxiaoman_entry");
    }
    
    if (body.finance_tab) {
      delete body.finance_tab;
      console.log("删除finance_tab");
    }

    // 用户VIP信息伪装
    if (body.user) {
      // 关闭摇一摇广告
      if (body.user.shake_ad_switch) {
        body.user.shake_ad_switch.is_show = 0;
        console.log("关闭摇一摇广告");
      }
    
      // VIP信息伪装
      if (body.user.vipInfo) {
        body.user.vipInfo.e_time = 1908965400; // VIP到期时间 (2030年)
        body.user.vipInfo.v_status = 1; // VIP状态
        body.user.vipInfo.stay_day = 1826; // VIP剩余天数
        body.user.vipInfo.v_level = 2; // VIP等级 (SVIP)
        console.log("伪装VIP信息");
      }
      
      // VIP显示信息
      if (body.user.vip_show_info) {
        body.user.vip_show_info.title = "超级会员";
        console.log("设置VIP显示标题");
      }
      
      // 付费会员信息
      if (body.user.pay_member_info) {
        body.user.pay_member_info.end_time = 1908965400;
        body.user.pay_member_info.props_id = 1050002; // SVIP的props_id
        console.log("伪装付费会员信息");
      }
      
      // VIP广告屏蔽权限
      if (body.user.vip_close_ad) {
        body.user.vip_close_ad.is_open = 1;
        body.user.vip_close_ad.vip_close = 1;
        body.user.vip_close_ad.shield_status = 1;
        body.user.vip_close_ad.live_close = 1;
        console.log("开启VIP广告屏蔽权限");
      }
      
      // 头像挂件
      if (body.user.pendant) {
        body.user.pendant.props_id = 2;
        console.log("设置VIP头像挂件");
      }
      
      // 设置用户VIP状态
      body.user.vip_status = 1;
      console.log("设置用户VIP状态");
    }
  
  // VIP横幅状态
  if (body.vip_banner) {
    body.vip_banner.vip_status = 1;
    console.log("设置VIP横幅状态");
  }
  
  // 过滤zone_info中的广告内容
  if (body.zone_info && Array.isArray(body.zone_info)) {
    const originalLength = body.zone_info.length;
    body.zone_info = body.zone_info.filter(item => {
      const blockedTypes = ["commerce", "banner", "game"];
      return !blockedTypes.includes(item.type);
    });
    if (body.zone_info.length < originalLength) {
      console.log(`过滤zone_info广告内容: ${originalLength - body.zone_info.length}个`);
    }
  }
  
  // SVIP数据伪装
  if (body.data && body.data.svip) {
    body.data.svip.default = 1;
    console.log("设置SVIP默认状态");
  }
  
  if (body.data && body.data.user) {
    body.data.user.vip_status = 1;
    if (body.data.user.pay_member_info) {
      body.data.user.pay_member_info.props_id = 1050002;
      body.data.user.pay_member_info.end_time = "1908965400";
    }
    console.log("伪装data.user VIP状态");
  }
}

// 直接全局搜索 @Modify(
if (url.includes("tiebaads/commonbatch") && method === postMethod) {
  // 看图模式下的广告
  let adCmd = getUrlParamValue(url, "adcmd");
  if (!adCmd) {
    console.log(`url:${url}`);
    $notification.post(
      notifyTitle,
      "贴吧-tiebaads/commonbatch",
      "adCmd参数不存在"
    );
  } else {
    console.log(`commonbatch:${adCmd}`);
    if (body.error_code === 0) {
      if (!body.res?.ad?.length) {
        console.log("ad字段为空");
      } else {
        body.res.ad = [];
        console.log("成功");
      }
    } else {
      console.log("error_code不为0:" + body.error_code);
    }
  }
} else if (url.includes("c/f/pb/picpage")) {
  console.log(`picpage`);
  const liveLength = body.recom_live_list?.length;
  if (liveLength) {
    console.log(`去除直播:${liveLength}`);
    body.recom_live_list = [];
  }
} else if (url.includes("c/s/sync")) {
  // get post(贴吧使用了post)均可访问
  console.log("贴吧-sync");
  if ("floating_icon" in body) {
    console.log("右下角悬浮icon");
    if (body.floating_icon) {
      if (body.floating_icon.homepage?.icon_url) {
        console.log("homepage悬浮去除");
      } else {
        console.log("无需去除homepage悬浮");
      }
      if (body.floating_icon.pb?.icon_url) {
        console.log("pb悬浮去除");
      } else {
        console.log("无需去除pb悬浮");
      }
      body.floating_icon = null;
    } else {
      console.log("无需修改floating_icon字段值");
    }
  } else {
    console.log(`body:${$response.body}`);
    $notification.post(notifyTitle, "贴吧-sync", "无floating_icon字段");
  }

  // 回帖栏的广告
  if ("advertisement_config" in body) {
    if (!body.advertisement_config?.advertisement_str) {
      console.log("无需处理advertisement_config");
    } else {
      console.log(
        `advertisement_str:${body.advertisement_config.advertisement_str}`
      );
      body.advertisement_config = null;
    }
  } else {
    console.log(`body:${$response.body}`);
    $notification.post(notifyTitle, "贴吧-sync", "无advertisement_config字段");
  }

  if ("config" in body) {
    if (body.config?.switch) {
      for (const item of body.config.switch) {
        // 穿山甲/广点通/快手
        if (
          [
            "platform_csj_init",
            "platform_ks_init",
            "platform_gdt_init",
            "platform_baidu_bqt_init",
            "platform_jy_init",
          ].includes(item.name)
        ) {
          if (item.type !== "0") {
            item.type = "0";
            console.log(`禁止初始化${item.name}`);
          }
        }
      }
    }
  } else {
    console.log(`body:${$response.body}`);
    $notification.post(notifyTitle, "贴吧-sync", "无config字段");
  }

  if ("screen_fill_data_result" in body) {
    if (
      body.screen_fill_data_result.screen_fill_advertisement_bear_switch === "1"
    ) {
      body.screen_fill_data_result.screen_fill_advertisement_bear_switch = "0";
      console.log("开屏不展示小熊广告");
    } else {
      console.log("无需修改screen_fill_advertisement_bear_switch");
    }
    if (
      body.screen_fill_data_result.screen_fill_advertisement_plj_cpc_switch ===
      "1"
    ) {
      body.screen_fill_data_result.screen_fill_advertisement_plj_cpc_switch =
        "0";
      console.log("开屏不展示序章CPC");
    } else {
      console.log("无需修改screen_fill_advertisement_plj_cpc_switch");
    }
    if (
      body.screen_fill_data_result.screen_fill_advertisement_plj_switch === "1"
    ) {
      body.screen_fill_data_result.screen_fill_advertisement_plj_switch = "0";
      console.log("开屏不展示序章");
    } else {
      console.log("无需修改screen_fill_advertisement_plj_switch");
    }
  } else {
    console.log(`body:${$response.body}`);
    $notification.post(
      notifyTitle,
      "贴吧-sync",
      "无screen_fill_data_result字段"
    );
  }

  if ("ad_stlog_switch" in body) {
    if (body.ad_stlog_switch === "1") {
      body.ad_stlog_switch = "0";
      console.log("修改ad_stlog_switch");
    } else {
      console.log("无需修改ad_stlog_switch");
    }
  } else {
    console.log(`body:${$response.body}`);
    $notification.post(notifyTitle, "贴吧-sync", "无ad_stlog_switch字段");
  }

  if ("lcs_strategy" in body) {
    // 控制长连接开关 开启时帖子会走socket
    if (body.lcs_strategy.conn_conf === "0") {
      // 关闭
      body.lcs_strategy.conn_conf = "1";
      console.log("修改conn_conf");
    } else {
      console.log("无需修改conn_conf");
    }
  } else {
    console.log(`body:${$response.body}`);
    $notification.post(notifyTitle, "贴吧-sync", "无lcs_strategy字段");
  }

  // 移除标签
  removeTabKeywords(body);

} else if (url.includes("c/f/frs/page")) {
  console.log("贴吧-FrsPage");
  if (body.live_fuse_forum?.length) {
    body.live_fuse_forum = [];
    console.log(`去除吧头直播`);
  } else {
    console.log(`无需处理吧头直播`);
  }

  if (body.activityhead?.is_ad) {
    body.activityhead = {};
    console.log("去除吧内header图片广告");
  } else {
    console.log("无需处理activityhead");
  }
  body.thread_list = removeLive(body.thread_list);
  removeGoodsInfo(body.forum?.banner_list?.app);
  
  // 在此接口中也尝试移除标签
  removeTabKeywords(body);
  
} else if (url.includes("c/f/frs/threadlist")) {
  console.log("贴吧-threadlist");
  removeGoodsInfo(body.banner_list?.app);
  
  // 在此接口中也尝试移除标签
  removeTabKeywords(body);
  
} else if (url.includes("c/f/pb/page")) {
  console.log("贴吧-PbPage");
  if (body.recom_ala_info?.live_id) {
    console.log("帖子详情页推荐的直播广告去除");
    body.recom_ala_info = null;
  } else {
    console.log("帖子详情页无直播广告");
  }

  if (body.post_list?.length) {
    for (const post of body.post_list) {
      if (post.outer_item) {
        console.log("outer_item去除");
        post.outer_item = null;
      }
    }
  } else {
    console.log("无需处理postList中的outer_item");
  }
  removeGoodsInfo(body.banner_list?.app);
  const bannerGoodsInfoLength =
    body.banner_list?.pb_banner_ad?.goods_info?.length;
  if (bannerGoodsInfoLength) {
    console.log(`去除pb_banner_ad的goods_info:${bannerGoodsInfoLength}`);
    body.banner_list.pb_banner_ad.goods_info = [];
  }
} else if (url.includes("c/f/excellent/personalized")) {
  console.log("贴吧-personalized");
  removeGoodsInfo(body.banner_list?.app);
  body.thread_list = removeLive(body.thread_list);
  if (body.live_answer) {
    console.log("去除推荐页上方的banner广告");
    body.live_answer = null;
  } else {
    console.log("推荐页无banner广告");
  }
  
  // 在此接口中也尝试移除标签
  removeTabKeywords(body);
  
} else if (url.includes("c/f/frs/generalTabList")) {
  console.log("贴吧-generalTabList");
  removeGoodsInfo(body.app_list);
} else if (url.includes("c/u/user/profile")) {
  console.log("贴吧-用户资料页-VIP伪装");
  fakeVIPStatus(body);
} else {
  // 对于未匹配的接口，也尝试移除标签
  const hasTabChanges = removeTabKeywords(body);
  if (!hasTabChanges) {
    $notification.post(notifyTitle, "路径/请求方法匹配错误:", method + "," + url);
  }
}

body = JSON.stringify(body);

$done({
  body,
});

function getUrlParamValue(url, queryName) {
  try {
    return Object.fromEntries(
      url
        .substring(url.indexOf("?") + 1)
        .split("&")
        .map((pair) => pair.split("="))
    )[queryName];
  } catch (e) {
    console.log(`获取URL参数失败: ${e.message}`);
    return null;
  }
}

function removeGoodsInfo(app) {
  if (app?.length) {
    let goodsInfoSize = 0;
    app.forEach((item) => {
      if (item.goods_info?.length) {
        goodsInfoSize++;
        item.goods_info = [];
      }
    });
    if (goodsInfoSize) {
      console.log(`去除goods_info:${goodsInfoSize}`);
    } else {
      console.log(`app内无goods_info`);
    }
  } else {
    console.log(`app为空,无需处理`);
  }
}

function removeLive(threadList) {
  let newThreadList = threadList;
  const beforeLength = threadList?.length;
  if (beforeLength) {
    newThreadList = threadList.filter((item) => {
      if (item.ala_info) {
        console.log("去除推荐的直播帖子");
        return false;
      }
      return true;
    });
    if (beforeLength === newThreadList.length) {
      console.log("无推荐的直播帖子");
    }
  } else {
    console.log("无需处理threadList");
  }
  return newThreadList;
}